<template>
  <div>
    <div style="margin: 10px 0">
      <el-input
          style="width: 200px"
          placeholder="请输入登录名、用户名"
          suffix-icon="el-icon-search"
          v-model="loginName"
      ></el-input>
      <el-button class="ml-5" type="primary" @click="load">搜索</el-button>
      <el-button type="warning" @click="reset">重置</el-button>
    </div>

    <div style="margin: 10px 0">
      <el-button type="primary" @click="handleAdd"
      >新增 <i class="el-icon-circle-plus-outline"></i
      ></el-button>

      <el-popconfirm
          class="ml-5"
          confirm-button-text="确定"
          cancel-button-text="等一下"
          icon="el-icon-info"
          icon-color="red"
          title="您确定要批量删除这些数据吗？"
          @confirm="delBatch"
      >
        <el-button type="danger" slot="reference"
        >批量删除 <i class="el-icon-remove-outline"></i
        ></el-button>
      </el-popconfirm>

      <el-upload
          :action="local+'/sysuser/import'"
          :show-file-list="false"
          accept="xlsx"
          :on-success="handleExcelImportSuccess"
          style="display: inline-block"
      >
        <el-button type="primary" class="ml-5"
        >导入 <i class="el-icon-upload2"></i
        ></el-button>
      </el-upload>
      <el-button
          type="primary" @click="exp" class="ml-5"
      >导出 <i class="el-icon-download"></i
      ></el-button>
    </div>

    <el-table
        :data="tableData"
        border
        stripe
        header-cell-class-name=".headerBg"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection"></el-table-column>
      <el-table-column prop="userId" label="编号" width="60"></el-table-column>
      <el-table-column prop="loginName" label="登录名"></el-table-column>
      <el-table-column prop="userName" label="用户名" width="140"></el-table-column>
      <el-table-column prop="deptId" label="部门"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="phonenumber" label="电话号码"></el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="warning" @click="handleQx(scope.row)"
          >权限 <i class="el-icon-lock"></i></el-button>
          <el-button type="success" @click="handleEdit(scope.row)"
          >编辑 <i class="el-icon-edit"></i
          ></el-button>
          <el-popconfirm
              class="ml-5"
              confirm-button-text="确定"
              cancel-button-text="等一下"
              icon="el-icon-info"
              icon-color="red"
              title="您确定要删除这一条数据吗？"
              @confirm="del(scope.row.userId)"
          >
            <el-button type="danger" slot="reference"
            >删除 <i class="el-icon-remove-outline"></i
            ></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div style="padding: 10px 0">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      >
      </el-pagination>
    </div>


    <el-dialog title="用户信息" :visible.sync="dialogFormVisible" width="30%">
      <el-form label-width="80px" size="small" ref="ruleFormRef" :model="form" :rules="rules">
        <el-form-item label="提示">
          <b style="color: #f56c6c;">新用户密码默认为:123456</b>
        </el-form-item>
        <el-form-item label="用户名" prop="loginName">
          <el-input v-model="form.loginName" :disabled="form.userId" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="userName">
          <el-input v-model="form.userName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
          <el-input v-model="form.deptId" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话号码" prop="phonenumber">
          <el-input v-model="form.phonenumber" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="showQuanXian" width="30%">
      <el-tree
          ref="treeRef"
          style="max-width: 600px"
          :data="allQuanXian"
          show-checkbox
          default-expand-all
          node-key="path"
          highlight-current
          :props="defaultProps"
      />
      <el-button @click="resetChecked">清空</el-button>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showQuanXian = false">取 消</el-button>
        <el-button type="primary" @click="saveQuanXian">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import router from "@/router";
import {LocalHost} from "@/utils/tools";

export default {
  name: "User",
  props: {
    user: Object,
  },
  data() {
    return {
      local: LocalHost,
      tableData: [],
      pageNum: 1,
      form: {},
      pageSize: 10,
      loginName: null,
      dialogFormVisible: false,
      showQuanXian: false,
      listQuanXian: [],
      allQuanXian: [],
      defaultProps: {children: 'children', label: 'name'},
      total: 0,
      multipleSelection: [],
      thisRow: null,
      title: null,
      rules: {
        loginName: [
          {required: true, message: '必填项', trigger: 'blur'},
          {min: 4, max: 10, message: '长度4-10', trigger: 'blur'},
        ],
        userName: [
          {required: true, message: '必填项', trigger: 'blur'},
          {min: 2, max: 10, message: '长度2-10', trigger: 'blur'},
        ],
        deptId: [
          {required: true, message: '必填项', trigger: 'blur'},
          {min: 2, max: 10, message: '长度2-10', trigger: 'blur'},
        ],
        email: [
          {min: 4, max: 20, message: '长度4-20', trigger: 'blur'},
        ],
        phonenumber: [
          {required: true, message: '必填项', trigger: 'blur'},
          {min: 11, max: 11, message: '长度11', trigger: 'blur'},
        ]
      }
    }
  },
  mounted() {
    this.allQuanXian = router['_path'].filter(item => {
      return ['home', 'person'].indexOf(item.path) < 0
    });
    this.load();
  },
  methods: {
    load() {
      this.request
          .get("/sysuser/page", {
            params: {
              pageNum: this.pageNum,
              pageSize: this.pageSize,
              loginName: this.loginName,
            },
          })
          .then((res) => {
            if (res.success) {
              this.tableData = res.data.records;
              this.total = res.data.total;
            }
          });
    },
    del(id) {
      this.request.delete("/sysuser/" + id).then((res) => {
        if (res.data) {
          this.$message.success("删除成功");
          this.load();
        } else {
          this.$message.error("删除失败");
        }
      });
    },
    delBatch() {
      if (this.multipleSelection.length < 1) {
        this.$message.warning("请勾选数据");
        return;
      }
      let ids = this.multipleSelection.map((v) => v.userId); //把对象数组变成纯id数组
      this.request.post("/sysuser/del/batch", ids).then((res) => {
        if (res.data) {
          this.$message.success("批量删除成功");
          this.load();
        } else {
          this.$message.error("批量删除失败");
        }
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleAdd() {
      this.dialogFormVisible = true;
      this.form = {};
    },
    handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row)); //可以解决编辑未确认就改变的问题
      this.dialogFormVisible = true;
    },
    handleQx(row) {
      this.thisRow = row;
      let me = this;
      this.title = '权限信息【' + row.userName + '】';
      this.$nextTick(() => {
        me.getQuanXian(row.userId);
      });

      this.showQuanXian = true;
    },
    save() {
      this.$refs.ruleFormRef.validate((valid, fields) => {
        if (valid) {
          this.request.post("/sysuser", this.form).then((res) => {
            if (res.data) {
              this.$message.success("保存成功");
              this.dialogFormVisible = false;
              this.load();
            } else {
              this.$message.error("保存失败");
            }
          });
        }
      })
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.load();
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum;
      this.load();
    },
    reset() {
      this.loginName = null;
      this.load();
    },
    exp() {
      window.open(this.local + "/sysuser/export");
    },
    handleExcelImportSuccess() {
      this.$message.success("导入成功");
      this.load();
    },
    getQuanXian(id) {
      if (id) {
        this.request.post("/sysuser/listUserRole", {id: id}).then((res) => {
          if (res.success) {
            this.listQuanXian = res.data;
            this.resetChecked();
            if (this.listQuanXian.length > 0) {
              this.$refs.treeRef.setCheckedKeys(this.listQuanXian.map(map => map.menuKey), false)
            }
          } else {
            this.$message.error("获取数据失败");
          }
        });
      }
    },
    saveQuanXian() {
      let checkedKeys = this.$refs.treeRef.getCheckedKeys(false);
      if (checkedKeys && checkedKeys.length > 0) {
        this.request.post("/sysuser/saveUserRole", {code: this.thisRow.userId, list: checkedKeys}).then((res) => {
          if (res.success) {
            this.showQuanXian = false;
            this.thisRow = null;
            this.$message.success("操作成功！")
          } else {
            this.$message.error("操作失败！")
          }
        })
      } else {
        this.$message.warning("至少要有一个权限！")
      }
    },
    resetChecked() {
      this.$refs.treeRef.setCheckedKeys([], false)
    }
  },
};
</script>

<style>
.headerBg {
  background: #eee !important;
}
</style>